from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
import time
import os

# 设置下载路径
download_dir = "/path/to/download/directory"

# 配置 Chrome 选项
chrome_options = webdriver.ChromeOptions()
prefs = {
    "download.default_directory": download_dir,  # 设置下载路径
    "download.prompt_for_download": False,       # 禁用下载提示
    "download.directory_upgrade": True,          # 允许下载到指定目录
    "safebrowsing.enabled": True                 # 启用安全浏览
}
chrome_options.add_experimental_option("prefs", prefs)

# 启动浏览器
service = ChromeService(executable_path="D:\Downloads\chromedriver-win64\chromedriver-win64\chromedriver.exe")
driver = webdriver.Chrome(service=service, options=chrome_options)

# 打开网页
driver.get("https://www.example.com/download")

# 点击下载按钮
download_button = driver.find_element(By.ID, "download-button")
download_button.click()

# 等待文件下载完成
time.sleep(10)  # 根据文件大小调整等待时间

# 检查文件是否下载成功
files = os.listdir(download_dir)
print("下载的文件列表:", files)

# 关闭浏览器
driver.quit()